package cn.kgc.sprignboot.redis.redis;

import cn.kgc.sprignboot.redis.utils.ApplicationContextUtil;
import org.apache.ibatis.cache.Cache;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;

/**
 * @author 课工场
 * @date 2024/12/3
 * @description   redis缓存   mybatis 二级缓存的实现方案
 */

public class RedisCache implements Cache {

    private final String id;


    //容器启动时 会调用该有参构造创建对象
    public RedisCache(String id) {
        this.id = id;
    }


    @Override
    public String getId() {
        return this.id;
    }


    // 保存缓存数据  redis
    @Override
    public void putObject(Object key, Object value) {
        HashOperations<String, Object, Object> hashOperations = createRedisTemplate().opsForHash();
        hashOperations.put(id,key,value);
    }


    //  获取缓存数据
    @Override
    public Object getObject(Object key) {
        return createRedisTemplate().opsForHash().get(id, key);
    }

    @Override
    public Object removeObject(Object key) {
        return null;
    }

    @Override
    public void clear() {
        // 清空redis中的该命名空间下的缓存
        createRedisTemplate().delete(id);
    }

    @Override
    public int getSize() {
        return 0;
    }


    // 获取操作hash类型数值的对象
    public RedisTemplate createRedisTemplate(){
        RedisTemplate redisTemplate = (RedisTemplate) ApplicationContextUtil.getBean("redisTemplate");
        redisTemplate.setKeySerializer(RedisSerializer.string());
        redisTemplate.setValueSerializer(RedisSerializer.string());
        return redisTemplate;
    }

}
